package com.ruoyi.pos.api.service.common.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.enums.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.json.JsonUtils;
import com.ruoyi.common.utils.leshua.LeshuaApiActiveInfoBean;
import com.ruoyi.common.utils.leshua.LeshuaApiBaseRequestBean;
import com.ruoyi.common.utils.leshua.LeshuaApiTransInfoBean;
import com.ruoyi.common.utils.leshua.LeshuaUtils;
import com.ruoyi.common.utils.map.MapLocalUtils;
import com.ruoyi.common.utils.qugongbao.QugongbaoUtils;
import com.ruoyi.common.utils.qugongbao.Signer;
import com.ruoyi.common.utils.rest.RestTemplateUtil;
import com.ruoyi.common.utils.rsa.RSAUtil;
import com.ruoyi.common.utils.shandianbao.ApiRequestBean;
import com.ruoyi.common.utils.shandianbao.ShandianbaoUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.weCat.WeCatUtils;
import com.ruoyi.common.utils.zhiqiangkeji.SignUtil;
import com.ruoyi.pos.api.dto.BaseDto;
import com.ruoyi.pos.api.dto.common.*;
import com.ruoyi.pos.api.service.common.ICommonService;
import com.ruoyi.pos.api.utils.CommonUtils;
import com.ruoyi.pos.api.vo.common.*;
import com.ruoyi.pos.api.vo.user.BankVo;
import com.ruoyi.pos.api.vo.user.TGoldRankingInfoVo;
import com.ruoyi.pos.api.vo.user.VipExplainVo;
import com.ruoyi.pos.web.domain.*;
import com.ruoyi.pos.web.mapper.*;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.apache.commons.compress.utils.Iterators;
import org.ini4j.MultiMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author luobo
 * @Date 2021/7/17 15:17
 */
@Service
public class CommonServiceImpl implements ICommonService {
    private static final Logger log = LoggerFactory.getLogger(CommonServiceImpl.class);
    @Autowired
    private Environment env;

    @Autowired
    private TUserInfoMapper userInfoMapper;
    @Autowired
    private TUserDefaultInfoMapper userDefaultInfoMapper;
    @Autowired
    private TPolicyInfoMapper policyInfoMapper;
    @Autowired
    private TSlideshowInfoMapper slideshowInfoMapper;
    @Autowired
    private TTerminalBrandInfoMapper terminalBrandInfoMapper;
    @Autowired
    private TTerminalGoodsInfoMapper terminalGoodsInfoMapper;
    @Autowired
    private TTerminalGoodsImgInfoMapper terminalGoodsImgInfoMapper;
    @Autowired
    private TTerminalGoodsSpeInfoMapper terminalGoodsSpeInfoMapper;
    @Autowired
    private TGoldDealSerialInfoMapper goldDealSerialInfoMapper;
    @Autowired
    private TGoldAwardSerialInfoMapper goldAwardSerialInfoMapper;
    @Autowired
    private TGoldInfoMapper goldInfoMapper;
    @Autowired
    private TAboutUsInfoMapper aboutUsInfoMapper;
    @Autowired
    private TGradeInfoMapper userGradeInfoMapper;
    @Autowired
    private TRebateSetInfoMapper rebateSetInfoMapper;
    @Autowired
    private TNavigationInfoMapper navigationInfoMapper;
    @Autowired
    private TSelfPickupPointInfoMapper selfPickupPointInfoMapper;
    @Autowired
    private TTerminalInfoMapper terminalInfoMapper;
    @Autowired
    private TTerminalBindInfoMapper terminalBindInfoMapper;
    @Autowired
    private TTerminalTransFlowInfoMapper terminalTransFlowInfoMapper;
    @Autowired
    private TWordOrderTypeInfoMapper wordOrderTypeInfoMapperl;
    @Autowired
    private TOrderInfoMapper orderInfoMapper;
    @Autowired
    private TGoldRankingInfoMapper goldRankingInfoMapper;
    @Autowired
    private TGradeInfoMapper tGradeInfoMapper;
    @Autowired
    private TBankInfoMapper tBankInfoMapper;
    @Autowired
    private ICommonService commonService;
    @Autowired
    private CommonUtils commonUtils; //公共业务处理类
    @Autowired
    private WeCatUtils weCatUtils; //微信业务处理类
    @Autowired
    RestTemplateUtil restTemplateUtil;
    @Autowired
    QugongbaoUtils qugongbaoUtils;
    @Autowired
    ShandianbaoUtils hufutianxiaUtils;


    @Override
    public Map<String, Object> queryGradeInfoList(BaseDto baseDto) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        PageUtil.startPage(baseDto);
        List<TGradeInfo> list = userGradeInfoMapper.selectTGradeInfoList(new TGradeInfo());
        List<GradeInfoVo> voList = new ArrayList<GradeInfoVo>();
        resultMap.put("total", 0L);
        Optional.ofNullable(list).ifPresent(lists -> {
            resultMap.put("total", new PageInfo(lists).getTotal());
            lists.stream().forEach(bean -> {
                GradeInfoVo vo = new GradeInfoVo();
                BeanUtils.copyProperties(bean, vo);
                voList.add(vo);
            });
        });
        resultMap.put("list", voList);
        return resultMap;
    }

    //查询系统基础配置信息
    @Override
    public TRebateSetInfo queryTRebateSetInfoVo() throws Exception {
        TRebateSetInfo mapper = new TRebateSetInfo();
        List<TRebateSetInfo> list = rebateSetInfoMapper.selectTRebateSetInfoList(mapper);
        if (null != list && list.size() > 0) {
            return list.get(0);
        }
        return new TRebateSetInfo();
    }

    //查询关于我们信息
    @Override
    public TAboutUsInfoVo queryTAboutUsInfoInfo() throws Exception {
        TAboutUsInfo mapper = new TAboutUsInfo();
        List<TAboutUsInfo> list = aboutUsInfoMapper.selectTAboutUsInfoList(mapper);
        TAboutUsInfoVo vo = new TAboutUsInfoVo();
        if (null != list && list.size() > 0) {
            BeanUtils.copyProperties(list.get(0), vo);
        }
        return vo;
    }

    //查询终端品牌列表
    @Override
    public List<TerminalBrandVo> queryTerminalBrandList() throws Exception {
        TTerminalBrandInfo mapper = new TTerminalBrandInfo();
        mapper.setIsValid(YesOrNoEnums.YES.getCode());
        List<TTerminalBrandInfo> list = terminalBrandInfoMapper.selectTTerminalBrandInfoList(mapper);
        List<TerminalBrandVo> voList = new ArrayList<TerminalBrandVo>();
        Optional.ofNullable(list).ifPresent(lists -> {
            lists.stream().forEach(bean -> {
                TerminalBrandVo vo = new TerminalBrandVo();
                BeanUtils.copyProperties(bean, vo);
                voList.add(vo);
                vo.setBrandId(bean.getId());
            });
        });
        return voList;
    }

    //查询终端商品列表
    @Override
    public Map<String, Object> queryTerminalGoodsList(TerminalGoodsDto terminalGoodsDto) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        TTerminalGoodsInfo mapper = new TTerminalGoodsInfo();
        BeanUtils.copyProperties(terminalGoodsDto, mapper);
        mapper.setIsValid(YesOrNoEnums.YES.getCode());
        if (StringUtils.isNotEmpty(terminalGoodsDto.getBrandId())) {
            mapper.setIsPopular("");
        }
        PageUtil.startPage(terminalGoodsDto);
        List<TTerminalGoodsInfo> list = terminalGoodsInfoMapper.selectTTerminalGoodsInfoList(mapper);
        List<TerminalGoodsVo> voList = new ArrayList<TerminalGoodsVo>();
        resultMap.put("total", 0L);
        Optional.ofNullable(list).ifPresent(lists -> {
            resultMap.put("total", new PageInfo(lists).getTotal());
            lists.stream().forEach(bean -> {
                TerminalGoodsVo vo = new TerminalGoodsVo();
                BeanUtils.copyProperties(bean, vo);
                vo.setGoodsId(bean.getId());
                vo.setGoodsTypeShow(Optional.ofNullable(GoodsTypeEnum.getEnumsByCode(bean.getGoodsType())).map(item -> item.getValue()).orElse(bean.getGoodsType()));
                vo.setGoodsStatusShow(Optional.ofNullable(GoodsStatusEnum.getGoodsStatusEnum(bean.getGoodsStatus())).map(item -> item.getValue()).orElse(bean.getGoodsStatus()));
                voList.add(vo);
            });
        });
        resultMap.put("list", voList);
        return resultMap;
    }

    //查询终端商品详情信息
    @Override
    public TerminalGoodsBuyVo queryTerminalGoodsDetail(TerminalGoodsDto terminalGoodsDto) throws Exception {
        TerminalGoodsBuyVo vo = new TerminalGoodsBuyVo();
        TTerminalGoodsInfo info = terminalGoodsInfoMapper.selectTTerminalGoodsInfoById(terminalGoodsDto.getGoodsId());
        BeanUtils.copyProperties(info, vo);
        vo.setGoodsTypeShow(Optional.ofNullable(GoodsTypeEnum.getEnumsByCode(info.getGoodsType())).map(item -> item.getValue()).orElse(info.getGoodsType()));
        vo.setGoodsStatusShow(Optional.ofNullable(GoodsStatusEnum.getGoodsStatusEnum(info.getGoodsStatus())).map(item -> item.getValue()).orElse(info.getGoodsStatus()));
        vo.setGoodsId(info.getId());
        //查询轮播图列表
        TTerminalGoodsImgInfo mapper = new TTerminalGoodsImgInfo();
        mapper.setGoodsId(terminalGoodsDto.getGoodsId());
        List<TTerminalGoodsImgInfo> imgs = terminalGoodsImgInfoMapper.selectTTerminalGoodsImgInfoList(mapper);
        List<TerminalGoodsBuyVo.ImgList> imgList = new ArrayList<TerminalGoodsBuyVo.ImgList>();
        Optional.ofNullable(imgs).ifPresent(list -> {
            list.stream().forEach(img -> {
                TerminalGoodsBuyVo.ImgList imgVo = new TerminalGoodsBuyVo.ImgList();
                BeanUtils.copyProperties(img, imgVo);
                imgList.add(imgVo);
            });
        });
        vo.setImgList(imgList);
        //查询规格列表
        TTerminalGoodsSpeInfo speMapper = new TTerminalGoodsSpeInfo();
        speMapper.setGoodsId(terminalGoodsDto.getGoodsId());
        List<TTerminalGoodsSpeInfo> spes = terminalGoodsSpeInfoMapper.selectTTerminalGoodsSpeInfoList(speMapper);
        List<TerminalGoodsBuyVo.SpeList> speList = new ArrayList<TerminalGoodsBuyVo.SpeList>();
        Optional.ofNullable(spes).ifPresent(list -> {
            list.stream().forEach(spe -> {
                TerminalGoodsBuyVo.SpeList speVo = new TerminalGoodsBuyVo.SpeList();
                BeanUtils.copyProperties(spe, speVo);
                speVo.setAmount(info.getAmount().multiply(spe.getGoodsNum()));//商品单价 * 规格数量
                speVo.setSpeId(spe.getId());
                speList.add(speVo);
            });
        });

        vo.setSpeList(speList);
        //终端购买提示
        List<TAboutUsInfo> tAboutUsInfos = aboutUsInfoMapper.selectTAboutUsInfoList(new TAboutUsInfo());
        vo.setBuyHint(tAboutUsInfos == null ? "" : tAboutUsInfos.get(0).getBuyHint());
        return vo;
    }

    //查询金刚导航栏列表
    @Override
    public List<NavigationInfoVo> queryNavigationInfoList() throws Exception {
        TNavigationInfo mapper = new TNavigationInfo();
        mapper.setIsValid(YesOrNoEnums.YES.getCode());
        List<TNavigationInfo> list = navigationInfoMapper.selectTNavigationInfoList(mapper);
        List<NavigationInfoVo> voList = new ArrayList<NavigationInfoVo>();
        Optional.ofNullable(list).ifPresent(lists -> {
            lists.stream().forEach(bean -> {
                NavigationInfoVo vo = new NavigationInfoVo();
                BeanUtils.copyProperties(bean, vo);
                voList.add(vo);
            });
        });
        return voList;
    }

    //图片类型(
    //1:首页弹窗,
    //2:首页轮播图,
    //3:广告展示,
    //4:分享图片,
    //5:腰部广告图
    //6:商户奖励背景图)
    @Override
    public Map<String, Object> queryTSlideshowInfoList(TSlideshowInfoDto slideshowInfoDto) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        TSlideshowInfo mapper = new TSlideshowInfo();
        mapper.setImgType(slideshowInfoDto.getImgType());
        mapper.setIsValid(YesOrNoEnums.YES.getCode());
        PageUtil.startPage(slideshowInfoDto);
        List<TSlideshowInfo> list = slideshowInfoMapper.selectTSlideshowInfoList(mapper);
        List<TSlideshowInfoVo> voList = new ArrayList<TSlideshowInfoVo>();
        TSlideshowInfoVo popup = new TSlideshowInfoVo();
        TSlideshowInfoVo loin = new TSlideshowInfoVo();
        if (slideshowInfoDto.getImgType().equals(ImgTypeEnums.ACTIVATED.getCode()) ||
                slideshowInfoDto.getImgType().equals(ImgTypeEnums.ADVERTISING.getCode()) ||
                slideshowInfoDto.getImgType().equals(ImgTypeEnums.BACKDROP.getCode())) {
            Optional.ofNullable(list).ifPresent(lists -> {
                lists.stream().forEach(bean -> {
                    TSlideshowInfoVo vo = new TSlideshowInfoVo();
                    BeanUtils.copyProperties(bean, vo);
                    resultMap.put("list", vo);
                });
            });
        } else {
            resultMap.put("total", 0L);
            Optional.ofNullable(list).ifPresent(lists -> {
                resultMap.put("total", new PageInfo(lists).getTotal());
                lists.stream().forEach(bean -> {
                    if (!bean.getImgType().equals(ImgTypeEnums.POPUP.getCode()) && !bean.getImgType().equals(ImgTypeEnums.LOIN.getCode())) {//轮播图
                        TSlideshowInfoVo vo = new TSlideshowInfoVo();
                        BeanUtils.copyProperties(bean, vo);
                        voList.add(vo);
                    } else if (bean.getImgType().equals(ImgTypeEnums.POPUP.getCode())) {//首页弹窗
                        BeanUtils.copyProperties(bean, popup);
                    } else if (bean.getImgType().equals(ImgTypeEnums.LOIN.getCode())) {//腰部广告图
                        BeanUtils.copyProperties(bean, loin);

                    }
                });
            });
            resultMap.put("popup", popup);
            resultMap.put("loin", loin);
            resultMap.put("list", voList);
        }

        return resultMap;
    }

    //查询平台政策/商学院列表
    @Override
    public Map<String, Object> queryPolicyInfoList(TPolicyInfoDto policyInfoDto) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        TPolicyInfo mapper = new TPolicyInfo();
        mapper.setType(policyInfoDto.getType());
        PageUtil.startPage(policyInfoDto);
        List<TPolicyInfo> list = policyInfoMapper.selectTPolicyInfoList(mapper);
        List<TPolicyInfoVo> voList = new ArrayList<TPolicyInfoVo>();
        resultMap.put("total", 0L);
        Optional.ofNullable(list).ifPresent(lists -> {
            resultMap.put("total", new PageInfo(lists).getTotal());
            lists.stream().forEach(bean -> {
                TPolicyInfoVo vo = new TPolicyInfoVo();
                BeanUtils.copyProperties(bean, vo);
                voList.add(vo);
            });
        });
        resultMap.put("list", voList);
        return resultMap;
    }

    //查询自提点列表
    @Override
    public List<TSelfPickupPointVo> querySelfPickupPointList(CommonDto commonDto) throws Exception {
        if (StringUtils.isEmpty(commonDto.getLng()) || StringUtils.isEmpty(commonDto.getLat())) {
            throw new RuntimeException("请先授权定位信息");
        }
        List<TSelfPickupPointVo> list = selfPickupPointInfoMapper.querySelfPickupPointList(commonDto);
        return list;
    }

    //根据微信回调信息，更新订单状态
    @Override
    public void weCatPayNotify(Map map) throws Exception {
        //启动子线程处理
        new Thread(() -> {
            try {
                notifyRun(map);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    //https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_2
    //回调处理
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public synchronized void notifyRun(Map map) throws Exception {
        String returnCode = (String) map.get("return_code");
        if ("SUCCESS".equals(returnCode)) { //支付回调的通知是成功的，根据回调的单号，重新查询微信支付结果接口，确保实际数据真实性
            Date date = DateUtils.getNowDate();
            String orderId = (String) map.get("out_trade_no");
            log.info("微信支付：交易记录编号：" + orderId);
            TOrderInfo order = orderInfoMapper.selectTOrderInfoById(orderId);
            Map<String, Object> resultMap = weCatUtils.queryOrderStatus(map);
            returnCode = (String) resultMap.get("return_code");
            Object result_code = resultMap.get("result_code"); //业务处理结果
            Object trade_state = resultMap.get("trade_state"); //交易结果
            if (null != returnCode
                    && "SUCCESS".equals(returnCode)
                    && null != result_code
                    && "SUCCESS".equals(result_code)) { //微信平台业务处理成功
                if (null != trade_state && "SUCCESS".equals(trade_state)) { //交易成功
                    //BigDecimal total_fee = BigDecimal.valueOf(Long.parseLong(resultMap.get("total_fee").toString())); //交易金额
                    //BigDecimal payAmount = order.getPayAmount().divide(new BigDecimal(100)); //微信支付的时候单位是分
                    //if (payAmount.compareTo(total_fee) == 0) { //暂时不校验金额
                    log.info("微信支付：订单id：" + orderId + "，支付成功");
                    order.setOrderStatus(OrderStatusEnums.WAIT_DELIVERED.getCode());
                    TUserInfo user = userInfoMapper.selectTUserInfoByUserId(order.getUserId());
                    if (!OrderTypeEnum.TERMINALPURCHASE.getCode().equals(order.getOrderType())) { //说明是兑换商品，处理兑换逻辑
                        handleExchangeOrder(order, user);
                    }
                    /*} else { //交易金额不对
                        log.info("微信支付：订单id："+ orderId + "，支付失败，微信支付金额：" + total_fee + "（分），与订单金额不匹配");
                        order.setOrderStatus(OrderStatusEnums.WAIT_PAY.getCode());
                    }*/
                } else { //交易失败
                    log.info("微信支付：订单id：" + orderId + "，支付失败，微信错误信息：" + resultMap.get("trade_state_desc"));
                    order.setOrderStatus(OrderStatusEnums.WAIT_PAY.getCode());
                }
            } else {
                log.info("微信支付：订单id：" + orderId + "，支付失败，微信错误信息：" + resultMap.get("err_code_des"));
                order.setOrderStatus(OrderStatusEnums.WAIT_PAY.getCode());
            }
            TOrderInfo orderNew = orderInfoMapper.selectTOrderInfoById(orderId);
            if (OrderStatusEnums.WAIT_PAY.getCode().equals(orderNew.getOrderStatus())) { //判断最新的订单状态，防止并发操作
                order.setUpdateTime(date);
                order.setPayTime(date);
                orderInfoMapper.updateTOrderInfo(order);
                log.info("微信支付：订单id：" + orderId + "，更新状态完成");
            } else {
                throw new RuntimeException("微信支付：不是待支付状态，不允许更新数据。订单id：" + orderId);
            }
        }
    }

    //处理兑换商品的兑换逻辑
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void handleExchangeOrder(TOrderInfo order, TUserInfo user) {
        TTerminalGoodsInfo goods = terminalGoodsInfoMapper.selectTTerminalGoodsInfoById(order.getGoodsId());
        TUserInfo goodsUser = userInfoMapper.selectTUserInfoByUserId(goods.getGoodsUserId());
        //转入
        TUserDefaultInfo goodsDefaultInfo = commonUtils.generateTUserDefaultInfo(
                goodsUser.getUserId(),
                order.getBrandId(),
                "",
                "",
                order.getExchangeAmount(),
                order.getId(),
                "",
                null,
                "",
                null);
        //转出
        TUserDefaultInfo defaultInfo = commonUtils.generateTUserDefaultInfo(
                user.getUserId(),
                order.getBrandId(),
                "",
                "",
                BigDecimal.ZERO.subtract(order.getExchangeAmount()),
                order.getId(),
                "",
                null,
                "",
                null);
        if (OrderTypeEnum.INTEGRALEXCHANGE.getCode().equals(order.getOrderType())) { //积分兑换
            user.setIntegralExchange(user.getIntegralExchange().add(order.getExchangeAmount()));
            goodsUser.setIntegralSum(goodsUser.getIntegralSum().add(order.getExchangeAmount()));
            goodsDefaultInfo.setTransType(TransTypeEnum.JIFEN.getCode());
            goodsDefaultInfo.setTransOperType(TransOperTypeEnum.JIFEN_2002.getCode());
            defaultInfo.setTransType(TransTypeEnum.JIFEN.getCode());
            defaultInfo.setTransOperType(TransOperTypeEnum.JIFEN_2003.getCode());
            userDefaultInfoMapper.insertTUserDefaultInfo(goodsDefaultInfo);
            userDefaultInfoMapper.insertTUserDefaultInfo(defaultInfo);
        } else if (OrderTypeEnum.TRANEXCHANGE.getCode().equals(order.getOrderType())) { //交易金兑换
            user.setDealGoldExchangeMark(user.getDealGoldExchangeMark().add(order.getExchangeAmount()));
            goodsUser.setDealGoldMark(goodsUser.getDealGoldMark().add(order.getExchangeAmount()));

            goodsDefaultInfo.setTransType(TransTypeEnum.JIAOYIJIN.getCode());
            goodsDefaultInfo.setTransOperType(TransOperTypeEnum.JIAOYIJIN_4002.getCode());
            defaultInfo.setTransType(TransTypeEnum.JIAOYIJIN.getCode());
            defaultInfo.setTransOperType(TransOperTypeEnum.JIAOYIJIN_4003.getCode());

            //t_gold_deal_serial_info
            TGoldDealSerialInfo mapper = new TGoldDealSerialInfo();
            mapper.setUserId(user.getUserId());
            mapper.setExchange(YesOrNoEnums.NO.getCode());
            PageUtil.startPage(0, order.getExchangeAmount().intValue());
            List<TGoldDealSerialInfo> list = goldDealSerialInfoMapper.selectTGoldDealSerialInfoList(mapper);
            Optional.ofNullable(list).ifPresent(lists -> {
                lists.stream().forEach(bean -> {
                    bean.setUserId(goodsUser.getUserId());
                    goldDealSerialInfoMapper.updateTGoldDealSerialInfo(bean);
                    TUserDefaultInfo defaultInfoStream = new TUserDefaultInfo();
                    TUserDefaultInfo goodsDefaultInfoStream = new TUserDefaultInfo();
                    BeanUtils.copyProperties(defaultInfo, defaultInfoStream);
                    defaultInfoStream.setId(IdUtils.simpleUUID());
                    defaultInfoStream.setSerialId(bean.getId());
                    BeanUtils.copyProperties(goodsDefaultInfo, goodsDefaultInfoStream);
                    goodsDefaultInfoStream.setId(IdUtils.simpleUUID());
                    goodsDefaultInfoStream.setSerialId(bean.getId());
                    userDefaultInfoMapper.insertTUserDefaultInfo(goodsDefaultInfoStream);
                    userDefaultInfoMapper.insertTUserDefaultInfo(defaultInfoStream);
                });
            });
        } else if (OrderTypeEnum.BONUSEXCHANGE.getCode().equals(order.getOrderType())) { //奖励金兑换
            user.setAwardGoldExchangeMark(user.getAwardGoldExchangeMark().add(order.getExchangeAmount()));
            goodsUser.setAwardGoldMark(goodsUser.getAwardGoldMark().add(order.getExchangeAmount()));

            goodsDefaultInfo.setTransType(TransTypeEnum.JIANGLIJIN.getCode());
            goodsDefaultInfo.setTransOperType(TransOperTypeEnum.JIANGLIJIN_5002.getCode());
            defaultInfo.setTransType(TransTypeEnum.JIANGLIJIN.getCode());
            defaultInfo.setTransOperType(TransOperTypeEnum.JIANGLIJIN_5003.getCode());

            //t_gold_award_serial_info
            TGoldAwardSerialInfo mapper = new TGoldAwardSerialInfo();
            mapper.setUserId(user.getUserId());
            mapper.setExchange(YesOrNoEnums.NO.getCode());
            PageUtil.startPage(0, order.getExchangeAmount().intValue());
            List<TGoldAwardSerialInfo> list = goldAwardSerialInfoMapper.selectTGoldAwardSerialInfoList(mapper);
            Optional.ofNullable(list).ifPresent(lists -> {
                lists.stream().forEach(bean -> {
                    bean.setUserId(goodsUser.getUserId());
                    goldAwardSerialInfoMapper.updateTGoldAwardSerialInfo(bean);
                    TUserDefaultInfo defaultInfoStream = new TUserDefaultInfo();
                    TUserDefaultInfo goodsDefaultInfoStream = new TUserDefaultInfo();
                    BeanUtils.copyProperties(defaultInfo, defaultInfoStream);
                    defaultInfoStream.setId(IdUtils.simpleUUID());
                    defaultInfoStream.setSerialId(bean.getId());
                    BeanUtils.copyProperties(goodsDefaultInfo, goodsDefaultInfoStream);
                    goodsDefaultInfoStream.setId(IdUtils.simpleUUID());
                    goodsDefaultInfoStream.setSerialId(bean.getId());
                    userDefaultInfoMapper.insertTUserDefaultInfo(goodsDefaultInfoStream);
                    userDefaultInfoMapper.insertTUserDefaultInfo(defaultInfoStream);
                });
            });
        } else if (OrderTypeEnum.GOLDEXCHANGE.getCode().equals(order.getOrderType())) { //金币兑换
            user.setGoldExchange(user.getGoldExchange().add(order.getExchangeAmount()));
            goodsUser.setGoldSum(goodsUser.getGoldSum().add(order.getExchangeAmount()));
            TGoldInfo mapper = new TGoldInfo();
            mapper.setUserId(user.getUserId());
            mapper.setExchange(YesOrNoEnums.NO.getCode());
            PageUtil.startPage(0, order.getExchangeAmount().intValue());
            List<TGoldInfo> list = goldInfoMapper.selectTGoldInfoList(mapper);
            Optional.ofNullable(list).ifPresent(lists -> {
                lists.stream().forEach(bean -> {
                    bean.setUserId(goodsUser.getUserId());
                    bean.setCreateTime(DateUtils.getNowDate());
                    goldInfoMapper.updateTGoldInfo(bean);
                });
            });
            goodsDefaultInfo.setTransType(TransTypeEnum.JINBI.getCode());
            goodsDefaultInfo.setTransOperType(TransOperTypeEnum.JINBI_3002.getCode());
            defaultInfo.setTransType(TransTypeEnum.JINBI.getCode());
            defaultInfo.setTransOperType(TransOperTypeEnum.JINBI_3003.getCode());
            userDefaultInfoMapper.insertTUserDefaultInfo(goodsDefaultInfo);
            userDefaultInfoMapper.insertTUserDefaultInfo(defaultInfo);
        }
        userInfoMapper.updateTUserInfo(user);
        userInfoMapper.updateTUserInfo(goodsUser);
    }

    //终端交易结果通知，终端产生交易时，第三方平台调用
    @Override
    @Transactional
    public JSONObject terminalTransResultNotify(String bodyStr, String sign) throws Exception {
        JSONObject result = new JSONObject();
        result.put("code", YesOrNoEnums.YES.getCode());
        if (RSAUtil.verify(bodyStr, env.getProperty("shande.publicKey"), sign)) { //验签
            log.info("杉德验签成功");
            TerminalTransResult bean = JsonUtils.jsonToPojo(bodyStr, TerminalTransResult.class);
            if (StringUtils.isEmpty(bean.getOrderId())) { //根据订单号查询该条记录是否存在
                result.put("desc", "订单号不能为空");
            } else {
                //校验数据是否需要落地
                if (("1".equals(bean.getPayType()) && !"1".equals(bean.getCardType())) //不是信用卡的刷卡记录，直接返回
                        || ("3".equals(bean.getPayType()) && !"6".equals(bean.getCardType()))) { //不是云闪付的闪付记录，直接返回
                    result.put("desc", "无效数据");
                    return result;
                }
                TTerminalInfo terminal = terminalInfoMapper.selectTTerminalInfoBySnCode(bean.getSnCode());
                if (null == terminal) {
                    result.put("desc", "无效终端数据");
                    return result;
                }
                Date transDate = DateUtils.dateTime(DateUtils.YYYYMMDDHHMMSS, bean.getTransTime());
                if (transDate.before(terminal.getAddTime())) {
                    result.put("desc", "历史交易记录，不做处理");
                    return result;
                }
                //处理业务逻辑
                TTerminalTransFlowInfo mapper = new TTerminalTransFlowInfo();
                mapper.setOrderId(bean.getOrderId());
                List<TTerminalTransFlowInfo> list = terminalTransFlowInfoMapper.selectTTerminalTransFlowInfoList(mapper);
                if (null != list && list.size() > 0) {
                    result.put("desc", "该订单已接收");
                } else { //数据落地
                    TTerminalTransFlowInfo flow = new TTerminalTransFlowInfo();
                    BeanUtils.copyProperties(bean, flow);
                    flow.setId(IdUtils.simpleUUID());
                    flow.setCreateTime(DateUtils.getNowDate());
                    flow.setIsValid(YesOrNoEnums.YES.getCode());
                    flow.setHandleStaus(HandleStausEnum.NO_HANDLE.getCode());
                    flow.setTransTime(transDate);
                    terminalTransFlowInfoMapper.insertTTerminalTransFlowInfo(flow);
                    result.put("code", YesOrNoEnums.NO.getCode());
                }
            }
        } else {
            log.info("杉德验签失败");
            result.put("desc", "验签失败");
        }
        return result;
    }

    //新增/变更商户结果通知，新增/变更商户时，第三方平台调用
    @Override
    @Transactional
    public JSONObject newMerchantNotify(String bodyStr, String sign) throws Exception {
        JSONObject result = new JSONObject();
        if (1 == 1) { //终端绑定状态根据交易结果通知进行判断，不再信任第三方推送的数据（20220108日变更内容）
            result.put("code", YesOrNoEnums.NO.getCode());
            return result;
        }
        result.put("code", YesOrNoEnums.YES.getCode());
        if (RSAUtil.verify(bodyStr, env.getProperty("shande.publicKey"), sign)) { //验签
            NewMerchant bean = JsonUtils.jsonToPojo(bodyStr, NewMerchant.class);
            if (StringUtils.isEmpty(bean.getAgentId())) { //
                result.put("desc", "订单号不能为空");
            } else {
                if (StringUtils.isEmpty(bean.getSnCode())) {
                    log.info("终端snCode为空，不处理该数据");
                    return result;
                }
                TTerminalInfo terminal = terminalInfoMapper.selectTTerminalInfoBySnCode(bean.getSnCode());
                if (null == terminal) {
                    result.put("desc", "无效终端数据");
                    return result;
                }
                //处理业务逻辑
                TTerminalBindInfo mapper = new TTerminalBindInfo();
                mapper.setSnCode(bean.getSnCode());
                List<TTerminalBindInfo> list = terminalBindInfoMapper.selectTTerminalBindInfoList(mapper);
                if (null != list && list.size() > 0) {
                    result.put("desc", "该订单已接收");
                } else {
                    TTerminalBindInfo bind = new TTerminalBindInfo();
                    BeanUtils.copyProperties(bean, bind);
                    bind.setId(IdUtils.simpleUUID());
                    bind.setCreateTime(DateUtils.getNowDate());
                    bind.setIsValid(YesOrNoEnums.YES.getCode());
                    terminalBindInfoMapper.insertTTerminalBindInfo(bind);
                    result.put("code", YesOrNoEnums.NO.getCode());
                }
                result.put("code", YesOrNoEnums.NO.getCode());
            }
        } else {
            result.put("desc", "验签失败");
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public String preCodeTransResultNotify(HttpServletRequest request) throws Exception {
        JSONObject reqPrams = new JSONObject();
        Enumeration<String> er = request.getParameterNames();
        while (er.hasMoreElements()) {
            String name = (String) er.nextElement();
            String value = request.getParameter(name);
            System.out.println("name：" + name + "------------value：" + value);
            reqPrams.put(name, value);
        }
        log.info("preCodeTransResultNotify接口获取的原始报文数据：" +  reqPrams.toJSONString());
        PreCodeTransResult bean = JsonUtils.jsonToPojo(reqPrams.toJSONString(), PreCodeTransResult.class);
        reqPrams.remove("sign");
        String localSign = SignUtil.getSign(reqPrams);
        System.out.println("----1---------" + localSign);
        if (StringUtils.isEmpty(bean.getSign())) {
            return "签名数据sign不能为空";
        }
        if (!bean.getSign().equalsIgnoreCase(localSign)) {
            return "验签失败";
        } else { //验签成功，数据落地
            log.info("店来宝验签成功");
            if (StringUtils.isEmpty(bean.getOrderId())) { //根据订单号查询该条记录是否存在
                log.info("支付系统订单号不能为空，订单号：" + bean.getOrderId());
                return "fail";
            } else {
                //校验数据是否需要落地
                //1-现金收款, 2-会员卡支付, 3-微信支付, 4-支付宝支付，5-云闪付
                if ("1".equals(bean.getProductType()) || ("2".equals(bean.getProductType()))) { //不是扫码或云闪付的记录，直接返回
                    log.info("无效数据，订单号：" + bean.getOrderId());
                    return "fail";
                }
                if (!"2".equals(bean.getStatus())) { //不是支付成功的数据，直接返回，不进行处理
                    log.info("无效数据，订单号：" + bean.getOrderId());
                    return "fail";
                }
                TTerminalInfo terminal = terminalInfoMapper.selectTTerminalInfoBySnCode(bean.getSnCode());
                if (null == terminal) {
                    log.info("无效终端数据，订单号：" + bean.getOrderId());
                    return "fail";
                }
                Date transDate = new Date();
                transDate.setTime(Long.valueOf(bean.getTradeSuccTime()));
                if (transDate.before(terminal.getAddTime())) {
                    log.info("历史交易记录，不做处理，订单号：" + bean.getOrderId() + "，第三方交易时间：" + bean.getTradeSuccTime());
                    return "fail";
                }
                //处理业务逻辑
                TTerminalTransFlowInfo mapper = new TTerminalTransFlowInfo();
                mapper.setOrderId(bean.getOrderId());
                List<TTerminalTransFlowInfo> list = terminalTransFlowInfoMapper.selectTTerminalTransFlowInfoList(mapper);
                if (null != list && list.size() > 0) {
                    log.info("该订单已接收，订单号：" + bean.getOrderId());
                    return "fail";
                } else { //数据落地
                    TTerminalTransFlowInfo flow = new TTerminalTransFlowInfo();
                    BeanUtils.copyProperties(bean, flow);
                    //交易方式转换
                    if ("3".equals(bean.getProductType()) || "4".equals(bean.getProductType())) { //支付产品类型: 1-现金收款, 2-会员卡支付, 3-微信支付, 4-支付宝支付，5-云闪付
                        flow.setPayType(PayTypeEnum.SAOMA_2.getCode());
                        flow.setCardType("2");
                    } else if ("5".equals(bean.getProductType())) {
                        flow.setPayType(PayTypeEnum.SHANFU_3.getCode());
                        flow.setCardType("6");
                    }
                    flow.setId(IdUtils.simpleUUID());
                    flow.setCreateTime(DateUtils.getNowDate());
                    flow.setIsValid(YesOrNoEnums.YES.getCode());
                    flow.setHandleStaus(HandleStausEnum.NO_HANDLE.getCode());
                    flow.setTransTime(transDate);
                    terminalTransFlowInfoMapper.insertTTerminalTransFlowInfo(flow);
                    log.info("处理成功，订单号：" + bean.getOrderId());
                    return "success";
                }
            }
        }
    }

    //乐刷交易结果通知，终端产生交易时，第三方平台调用
    @Override
    @Transactional
    public String leshuaTransResultNotify(LeshuaApiBaseRequestBean bean) throws Exception {
        log.info("乐刷请求参数：{}", bean);
        if (StringUtils.isEmpty(bean.getSign())) {
            log.info("乐刷签名数据sign不能为空");
            return "签名数据sign不能为空";
        }
        Map<String, Object> map = MapLocalUtils.beanToMap(bean);
        map.remove("sign");
        String localSign = LeshuaUtils.getSign(map);
        //if (!bean.getSign().equalsIgnoreCase(localSign)) {
        if (bean.getSign().equalsIgnoreCase(localSign)) {
            log.info("乐刷验签失败");
            return "乐刷验签失败";
        } else {
            log.info("乐刷验签成功");
            List<LeshuaApiTransInfoBean> transList = JsonUtils.jsonToList(bean.getData(), LeshuaApiTransInfoBean.class);
            if (null != transList && transList.size() > 0) {
                for (LeshuaApiTransInfoBean  trans : transList) {
                    if (StringUtils.isEmpty(trans.getOrderId())) { //根据订单号查询该条记录是否存在
                        log.info("乐刷支付系统订单号不能为空，订单号：" + trans.getOrderId());
                        return "fail";
                    } else {
                        TTerminalInfo terminal = terminalInfoMapper.selectTTerminalInfoBySnCode(trans.getSnCode());
                        if (null == terminal) {
                            log.info("乐刷无效终端数据，订单号：" + trans.getOrderId());
                            return "fail";
                        }
                        Date transDate = new Date();
                        transDate.setTime(Long.valueOf(trans.getTransTime()));
                        if (transDate.before(terminal.getAddTime())) {
                            log.info("乐刷历史交易记录，不做处理，订单号：" + trans.getOrderId() + "，第三方交易时间：" + trans.getTransTime());
                            return "fail";
                        }
                        //处理业务逻辑
                        TTerminalTransFlowInfo mapper = new TTerminalTransFlowInfo();
                        mapper.setOrderId(trans.getOrderId());
                        List<TTerminalTransFlowInfo> list = terminalTransFlowInfoMapper.selectTTerminalTransFlowInfoList(mapper);
                        if (null != list && list.size() > 0) {
                            log.info("乐刷该订单已接收，订单号：" + trans.getOrderId());
                            return "fail";
                        } else { //数据落地
                            TTerminalTransFlowInfo flow = new TTerminalTransFlowInfo();
                            BeanUtils.copyProperties(trans, flow);
                            //交易方式转换
                            if (PayTypeEnum.LESHUA_1_SALE.getCode().equals(trans.getPayType()) && !"2".equals(trans.getCardType())) { //说明是不是刷的信用卡，不要此种数据
                                continue;
                            } else if (PayTypeEnum.LESHUA_3_QSALE.getCode().equals(trans.getPayType())) { //处理闪付类型
                                flow.setCardType("6");
                            }
                            flow.setId(IdUtils.simpleUUID());
                            flow.setCreateTime(DateUtils.getNowDate());
                            flow.setIsValid(YesOrNoEnums.YES.getCode());
                            flow.setHandleStaus(HandleStausEnum.NO_HANDLE.getCode());
                            flow.setTransTime(transDate);
                            terminalTransFlowInfoMapper.insertTTerminalTransFlowInfo(flow);
                            log.info("乐刷处理成功，订单号：" + trans.getOrderId());
                            return "success";
                        }
                    }
                }
            }
        }
        return "success";
    }

    //乐刷激活交易结果通知，终端产生交易时，第三方平台调用
    @Override
    public String leshuaActiveResultNotify(LeshuaApiBaseRequestBean bean) throws Exception {
        log.info("请求参数：{}", bean);
        if (StringUtils.isEmpty(bean.getSign())) {
            log.info("签名数据sign不能为空");
            return "签名数据sign不能为空";
        }
        JSONObject reqPrams = JSONObject.parseObject(bean.getData());
        String localSign = LeshuaUtils.getSign(reqPrams);
        if (!bean.getSign().equalsIgnoreCase(localSign)) {
            log.info("乐刷验签失败");
            return "乐刷验签失败";
        } else {
            log.info("乐刷验签成功");
            LeshuaApiActiveInfoBean transBean = JsonUtils.jsonToPojo(bean.getData(), LeshuaApiActiveInfoBean.class);
            /*if (StringUtils.isEmpty(transBean.getTrans_id())) { //根据订单号查询该条记录是否存在
                log.info("支付系统订单号不能为空，订单号：" + transBean.getTrans_id());
                return "fail";
            } else {

            }*/
            TTerminalTransFlowInfo flow = new TTerminalTransFlowInfo();
            flow.setCreateTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, transBean.getActivation_time()));
            flow.setId(IdUtils.simpleUUID());
            flow.setHandleResult(YesOrNoEnums.NO.getCode());
            flow.setHandleResult(transBean.getActivation_type());
            flow.setTransAmount(new BigDecimal(transBean.getDeposit_amount()));
            terminalTransFlowInfoMapper.insertTTerminalTransFlowInfo(flow);
        }
        return "success";
    }

    public static void main(String[] args) {
        String ss = "{\"dataList\":[{\"code\":\"9998\",\"idCardNo\":\"420222222222222222\",\"memberName\":\"萝卜\",\"mobile\":\"13669001897\",\"msg\":\"身份证无效\"}]}";
        List<MemberRegDto> dto = JsonUtils.jsonToList(JSONObject.parseObject(ss).getString("dataList"), MemberRegDto.class);
        System.out.println(dto);
    }

    //趣工宝注册接口
    @Override
    public JSONObject memberRegUrl(String userName, String userPhone, String idCardNo, String bankCardNo) throws Exception {
        JSONObject jo = qugongbaoUtils.memberRegUrl(userName, userPhone, idCardNo, "BANK", bankCardNo);
        if ("0000".equals(jo.get("code")) && StringUtils.isNotNull(jo.get("body"))) {
            List<MemberRegDto> list = JsonUtils.jsonToList(JSONObject.parseObject(jo.get("body").toString()).getString("dataList"), MemberRegDto.class);
            Optional.ofNullable(list).ifPresent(lists ->{
                lists.stream().forEach(bean ->{
                    if ("0000".equals(bean.getCode())) {
                        System.out.println(bean.getMemberName() + "-------" + bean.getMemberNo());
                    } else {
                        throw new RuntimeException("获取趣工宝会员编号失败，失败信息：" + bean.getMsg());
                    }
                });
            });
            return jo;
        } else { //注册申请失败
            throw new RuntimeException("注册申请失败：" + jo.get("msg"));
        }
    }

    //趣工宝签约接口
    @Override
    public JSONObject signContract(String memberNo, String serverCallbackUrl, String pageCallbackUrl) throws Exception {
        JSONObject jo = qugongbaoUtils.signContract(memberNo, serverCallbackUrl, pageCallbackUrl);
        if ("0000".equals(jo.get("code")) && StringUtils.isNotNull(jo.get("body"))) {
            String contractUrl = JSONObject.parseObject(jo.get("body").toString()).getString("contractSignUrl");
            String contractNo = JSONObject.parseObject(jo.get("body").toString()).getString("contractNo");
            return JSONObject.parseObject(jo.get("body").toString());
        } else { //签约申请失败
            throw new RuntimeException("签约申请失败");
        }
    }

    //趣工宝变更银行卡接口
    @Override
    public boolean updateBankCard(String memberNo, String bankCardNo) throws Exception {
        return qugongbaoUtils.updateBankCard(memberNo, bankCardNo);
    }

    //趣工宝签约信息查询接口
    @Override
    public JSONObject getMemberInfo(String memberNo) throws Exception {
        JSONObject jo = qugongbaoUtils.getMemberInfo(memberNo);
        if ("0000".equals(jo.get("code")) && StringUtils.isNotNull(jo.get("body"))) {
            return JSONObject.parseObject(jo.get("body").toString());
        } else { //签约申请失败
            throw new RuntimeException("签约状态信息查询失败：" + jo.get("msg"));
        }
    }

    //趣工宝签约接口
    @Override
    public JSONObject queryContractStatus(String memberNo, String spCode) throws Exception {
        JSONObject jo = qugongbaoUtils.queryContractStatus(memberNo, spCode);
        if ("0000".equals(jo.get("code")) && StringUtils.isNotNull(jo.get("body"))) {
            String contractUrl = JSONObject.parseObject(jo.get("body").toString()).getString("contractSignUrl");
            String contractNo = JSONObject.parseObject(jo.get("body").toString()).getString("contractNo");
            return JSONObject.parseObject(jo.get("body").toString());
        } else { //签约申请失败
            throw new RuntimeException("签约状态查询失败：" + jo.get("msg"));
        }
    }

    //趣工宝提现接口
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Map<String, String> withdrawalForPay() throws Exception {
        TUserDefaultInfo defaultInfo = userDefaultInfoMapper.selectTUserDefaultInfoById("19d1bf3a03204bc7bf5a09c2b0f2b308");
        BigDecimal transAmount = defaultInfo.getTransAmount().subtract(defaultInfo.getServiceChargeAmount()).multiply(new BigDecimal(100));
        TUserInfo user = userInfoMapper.selectTUserInfoByUserId(defaultInfo.getUserId());
        Map<String, String> resultMap = qugongbaoUtils.withdrawalForPay(defaultInfo.getId(), defaultInfo.getId(), user.getMemberNo(), transAmount);
        if ("0000".equals(resultMap.get("code"))) {
            return resultMap;
        } else { //提现申请失败
            throw new RuntimeException("提现申请失败");
        }
    }

    //趣工宝提现状态查询接口
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Map<String, String> withdrawalResultQuery() throws Exception {
        String custTransId = "036a09a364f84edd8d6b886c89e23a33";
        Map<String, String> responseMap = qugongbaoUtils.withdrawalResultQuery(custTransId);
        return responseMap;
    }

    //趣工宝提现结果通知接口
    @Override
    @Transactional
    public JSONObject withdrawalResultNotify(WithdrawalResultNotifyDto dto) throws Exception {
        String jsonStr = JsonUtils.objToJson(dto);
        log.info("请求原始数据为：" + jsonStr);
        JSONObject result = new JSONObject();
        result.put("code", YesOrNoEnums.YES.getCode());
        Map<String, String> responseMap = JSON.parseObject(JsonUtils.objToJson(dto), new TypeReference<Map<String, String>>() {});
        if (StrUtil.isNotBlank(responseMap.get(Signer.SIGN_VALUE))) {
            if (Signer.verify(responseMap, env.getProperty("qugongbao.publicKey"))) { //验签成功
                log.info("趣工宝验签成功");
                JSONObject jo = JSONObject.parseObject(dto.getBody());
                //"{\"custNo\":\"108120211201092245\",\"custOrderNo\":\"036a09a364f84edd8d6b886c89e23a33\",\"orderNo\":\"20211201140272274004\",\"status\":3}"
                String status = jo.get("status").toString(); //付款明细状态 //2：处理中 ；3：成功；4：部分成功；5:失败
                log.info("趣工宝提现状态：" + status + ",数据主键：" + jo.get("custOrderNo").toString());
                TUserDefaultInfo defaultInfo = userDefaultInfoMapper.selectTUserDefaultInfoById(jo.get("custOrderNo").toString());
                if (null == defaultInfo) {
                    result.put("desc", "无效的提现单号");
                    return result;
                }
                if (!AuditStatusEnum.PASS_AUDIT.getCode().equals(defaultInfo.getCheckStatus()) || !WithdrawStatusEnum.HANDEL.getCode().equals(defaultInfo.getWithdrawStatus())) {
                    result.put("desc", "不是处理中状态，不能更新本地数据");
                    return result;
                }
                TUserInfo user = userInfoMapper.selectTUserInfoByUserId(defaultInfo.getUserId());
                if ("3".equals(status)) { //成功
                    if (StringUtils.isNotEmpty(user.getSuperiorUserId())) {
                        //提现分润，用户提现成功，直营上级会获得分润收益
                        TRebateSetInfo set = commonService.queryTRebateSetInfoVo();
                        TUserDefaultInfo supDefaultInfo = commonUtils.generateTUserDefaultInfo(
                                user.getSuperiorUserId(),
                                "",
                                TransTypeEnum.YUE.getCode(),
                                TransOperTypeEnum.YUE_1008.getCode(),
                                defaultInfo.getWithdrawAmount().multiply(set.getCarryRebate()).setScale(2, BigDecimal.ROUND_HALF_DOWN),
                                "",
                                "",
                                null,
                                "",
                                null);
                        userDefaultInfoMapper.insertTUserDefaultInfo(supDefaultInfo);
                        TUserInfo supUser = userInfoMapper.selectTUserInfoByUserId(user.getSuperiorUserId());
                        supUser.setBalanceSum(supUser.getBalanceSum().add(supDefaultInfo.getTransAmount()));
                        userInfoMapper.updateTUserInfo(supUser);
                    }
                    defaultInfo.setWithdrawStatus(WithdrawStatusEnum.SUCCESS.getCode());
                    defaultInfo.setWithdrawStatusTime(DateUtils.getNowDate());
                } else if ("5".equals(status)) { //失败
                    //msg，失败原因
                    defaultInfo.setWithdrawStatus(WithdrawStatusEnum.FAIL.getCode());
                    defaultInfo.setWithdrawStatusTime(DateUtils.getNowDate());
                    //提现失败的时候，还原已提现额度
                    BigDecimal amount = defaultInfo.getTransAmount().add(defaultInfo.getServiceChargeAmount());
                    user.setBalanceWithdraw(user.getBalanceWithdraw().subtract(amount));
                    userInfoMapper.updateTUserInfo(user);
                }
                userDefaultInfoMapper.updateTUserDefaultInfo(defaultInfo);
                log.info("趣工宝提现结果处理成功");
                result.put("desc", "处理成功");
            } else {
                log.info("趣工宝验签失败");
                result.put("desc", "验签失败");
            }
        }
        return result;
    }

    //趣工宝提现退票查询接口
    @Override
    @Transactional
    public JSONObject withdrawalResultForRefund(WithdrawalRefundResultNotifyDto dto) throws Exception {
        String jsonStr = JsonUtils.objToJson(dto);
        log.info("请求原始数据为：" + jsonStr);
        JSONObject result = new JSONObject();
        result.put("code", YesOrNoEnums.YES.getCode());
        Map<String, String> responseMap = JSON.parseObject(JsonUtils.objToJson(dto), new TypeReference<Map<String, String>>() {});
        if (StrUtil.isNotBlank(responseMap.get(Signer.SIGN_VALUE))) {
            if (Signer.verify(responseMap, env.getProperty("qugongbao.publicKey"))) { //验签成功
                log.info("趣工宝验签成功");
                JSONObject jo = JSONObject.parseObject(dto.getBody());
                //退票明细状态 //1: 未退票，2：退票处理中；3已退票
                //"{"amount":52673,"custOrderNo":"3bd4434cf153463f8d5fd77c2dae6f5d","custTransId":"3bd4434cf153463f8d5fd77c2dae6f5d","errMsg":"账号解析失败或账号状态异常","memberName":"顾筑临","memberNo":"21420022408831700992","orderNo":"20220308232778033638","refundDate":"20220308","refundStatus":3,"taskFee":3687}"
                TUserDefaultInfo defaultInfo = userDefaultInfoMapper.selectTUserDefaultInfoById(jo.get("custOrderNo").toString());
                if (null == defaultInfo) {
                    result.put("desc", "无效的提现单号");
                    return result;
                }
                if (!AuditStatusEnum.PASS_AUDIT.getCode().equals(defaultInfo.getCheckStatus()) || !WithdrawStatusEnum.SUCCESS.getCode().equals(defaultInfo.getWithdrawStatus())) {
                    result.put("desc", "不是提现成功状态，不能更新本地数据");
                    return result;
                }
                String refundStatus = jo.get("refundStatus").toString();
                if ("3".equals(refundStatus)) { //1: 未退票，2：退票处理中；3已退票
                    TUserInfo user = userInfoMapper.selectTUserInfoByUserId(defaultInfo.getUserId());
                    user.setBalanceWithdraw(user.getBalanceWithdraw().subtract(defaultInfo.getTransAmount())); //还原已提现额度
                    userInfoMapper.updateTUserInfo(user);
                    defaultInfo.setWithdrawStatus(WithdrawStatusEnum.FAILFORBANK.getCode());
                    defaultInfo.setWithdrawStatusTime(DateUtils.getNowDate());
                    userDefaultInfoMapper.updateTUserDefaultInfo(defaultInfo);
                    log.info("趣工宝提现退票结果处理成功");
                    result.put("desc", "处理成功");
                } else {
                    log.info("不是退票成功的数据，不处理");
                    result.put("desc", "不是退票成功的数据，不处理");
                }
            } else {
                log.info("趣工宝验签失败");
                result.put("desc", "验签失败");
            }
        }
        return result;
    }

    //趣工宝签约结果通知
    @Override
    @Transactional
    public JSONObject signContractResultNotify(WithdrawalResultNotifyDto dto) throws Exception {
        String jsonStr = JsonUtils.objToJson(dto);
        log.info("请求原始数据为：" + jsonStr);
        JSONObject result = new JSONObject();
        result.put("code", YesOrNoEnums.YES.getCode());
        Map<String, String> responseMap = JSON.parseObject(JsonUtils.objToJson(dto), new TypeReference<Map<String, String>>() {});
        if (StrUtil.isNotBlank(responseMap.get(Signer.SIGN_VALUE))) {
            if (Signer.verify(responseMap, env.getProperty("qugongbao.publicKey"))) { //验签成功
                log.info("趣工宝签约验签成功");
                JSONObject jo = JSONObject.parseObject(dto.getBody());
                String contractStatus = jo.getString("contractStatus"); //签约状态 //0：未签约 1：处理中 2：签约成功 3：签约失败
                String memberNo = jo.getString("memberNo"); //会员编号
                TUserInfo user = userInfoMapper.selectUserByUserMemberNo(memberNo);
                JSONObject signJo = qugongbaoUtils.queryContractStatus(memberNo, user.getContractNo());
                if (null == user) {
                    result.put("desc", "无效的会员编号");
                    return result;
                }
                if (AuditStatusEnum.PASS_AUDIT.getCode().equals(user.getSignStatus())) {
                    result.put("desc", "签约成功不能再进行签约");
                    return result;
                }
                if ("2".equals(contractStatus)) { //成功
                    user.setSignStatus(AuditStatusEnum.PASS_AUDIT.getCode());
                    user.setSignTime(DateUtils.getNowDate());
                    user.setContractName(signJo.getString("contractName"));
                    user.setContractUrl(signJo.getString("downloadUrl"));
                } else if ("3".equals(contractStatus)) { //失败
                    //msg，失败原因
                    user.setSignStatus(AuditStatusEnum.REFUSE_AUDIT.getCode());
                    user.setSignTime(DateUtils.getNowDate());
                }
                userInfoMapper.updateTUserInfo(user);
                log.info("趣工宝签约结果处理成功");
                result.put("desc", "处理成功");
            } else {
                log.info("趣工宝签约验签失败");
                result.put("desc", "验签失败");
            }
        }
        return result;
    }


    //查询工单类型
    @Override
    public List<TWordOrderTypeInfo> queryTWordOrderTypeInfoList() throws Exception {
        TWordOrderTypeInfo wordOrderTypeInfo = new TWordOrderTypeInfo();
        wordOrderTypeInfo.setIsValid(YesOrNoEnums.YES.getCode());//查询正常状态下的所有工单类型
        List<TWordOrderTypeInfo> list = wordOrderTypeInfoMapperl.selectTWordOrderTypeInfoList(wordOrderTypeInfo);
        return list;
    }

    //英雄交易帮
    @Override
    public List<TGoldRankingInfoVo> queryTGoldRankingInfo(String dealAwardType) throws Exception {
        TGoldRankingInfo tGoldRankingInfo = new TGoldRankingInfo();
        tGoldRankingInfo.setDealAwardType(dealAwardType);
        BaseDto baseDto = new BaseDto();
        baseDto.setPageNum(1);
        baseDto.setPageSize(10);
        PageUtil.startPage(baseDto);
        List<TGoldRankingInfo> tGoldRankingInfos = goldRankingInfoMapper.selectTGoldRankingInfoList(tGoldRankingInfo);
        List<TGoldRankingInfoVo> listVo = new ArrayList<>();
        for (TGoldRankingInfo goldRankingInfo : tGoldRankingInfos) {
            TGoldRankingInfoVo infoVo = new TGoldRankingInfoVo();
            BeanUtils.copyProperties(goldRankingInfo, infoVo);
            listVo.add(infoVo);
        }
        return listVo;
    }


    //vip基础说明
    @Override
    public List<VipExplainVo> queryVipExplain() throws Exception {
        List<VipExplainVo> listVo = new ArrayList<>();
        List<TGradeInfo> tGradeInfos = tGradeInfoMapper.queryUserVip();
        Optional.ofNullable(tGradeInfos).ifPresent(map -> {
            map.stream().forEach(bean -> {
                VipExplainVo vo = new VipExplainVo();
                BeanUtils.copyProperties(bean, vo);
                listVo.add(vo);
            });
        });
        return listVo;
    }

    /*银行维护*/
    @Override
    public List<BankVo> queryBankList() throws Exception {
        List<TBankInfo> tBankInfos = tBankInfoMapper.selectTBankInfoList(new TBankInfo());
        List<BankVo> listVo = new ArrayList<>();
        tBankInfos.stream().forEach(bean -> {
            BankVo vo = new BankVo();
            BeanUtils.copyProperties(bean, vo);
            listVo.add(vo);
        });
        return listVo;
    }

    ;

    /*微信授权空白页域名*/
    @Override
    public String getAuthorizationUrl(String url) throws Exception {
        //String authorRedirectUri = env.getProperty("wx.authorRedirectUri");
        return weCatUtils.getAuthorizationUrl(url);
    }

    /*微信公众号签名授权*/
    @Override
    public Map<String, String> getPermissionsToSign(String url) throws Exception {
        //String authorRedirectUri = env.getProperty("wx.authorRedirectUri");
        return weCatUtils.getPermissionsToSign(url);
    }

    /*code换openId*/
    @Override
    public JSONObject queryWxOpenId(String code) throws Exception {
        return weCatUtils.queryWxOpenId(code);
    }
}
